var title;

layui.use(['form'], function () {
    var form = layui.form,
        layer = layui.layer,
        $ = layui.$;

    //监听提交
    form.on('submit(saveBtn)', function (data) {
        // console.log("debug data:",addOrderTemp(data.field));
        // 发送请求
        $.ajax({
            url:'/OrderTemp/add',
            type:"post",
            data:JSON.stringify(addOrderTemp(data.field)),
            dataType:"json",
            contentType:'application/json',  // 声明发送数据格式
            // processData:false,   // 浏览器不要影响数据
            beforeSend:()=>{
                var index = layer.alert(JSON.stringify(data.field), {
                    title: '最终的提交信息'
                }, function () {
                    // 关闭弹出层
                    layer.close(index);

                    var iframeIndex = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(iframeIndex);
                });
            }
            
        });
        return false;
    });

});

function uuid(){
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function (c) {
		var r =Math.random() * 16 | 0 ,
		 v = c == 'x' ? r: (r & 0x3|0x8);
		return v.toString(16);
	})
}

function init(){
    let jsonexcel;
    var selectObj = document.getElementById("sheetNames");

    // 监听member-file变更，更新sheetNames下拉列表
    document.getElementById('order-file').addEventListener('change', function(e) {   //选择文件后执行
        // 清理下拉列表（sheetNames）
        $('#sheetNames option').remove();

        var optEle1 = document.createElement("option");
        optEle1.setAttribute("value","default");
        optEle1.appendChild(document.createTextNode("==选择sheetname=="));
        selectObj.appendChild(optEle1);

        let  files = e.target.files;
        if(files.length == 0) return;
        let  file = files[0];
        let  reader = new FileReader();
        reader.readAsBinaryString(file);
        reader.onload = function(e) {   //处理load事件。读取操作完成时触发。
            let  data = e.target.result;
            
            workbook = XLSX.read(data, {type: 'binary'}); //XLSX：/xlsx.core.min.js 通过XLSX.read(data, {type: type})方法读取excel 后面介绍

            let  sheetNames = workbook.SheetNames; // 工作表名称集合
            for (i = 0;i<sheetNames.length;i++) {
                            
                // 填充sheetname下拉列表
                var optEle2 = document.createElement("option");
                optEle2.setAttribute("value",sheetNames[i]);
                optEle2.appendChild(document.createTextNode(sheetNames[i]));
                selectObj.appendChild(optEle2);
            }
            layui.form.render("select");
        };
    });

    var dealerSelect = document.getElementById("dealer_id");
    $.ajax({
        url: '/Dealer/list',
        type: "post",
        data: `{"page":1,"limit":15}`,
        datatype: "json",
        success: function (data) {
            console.log("Debug data:", data);
            let optEle1 = document.createElement("option");
            // optEle1.setAttribute("value","default");
            dealerSelect.appendChild(optEle1);
            for (var x = 0; x < data.data.length; x++) {
                let optEle1 = document.createElement("option");
                optEle1.setAttribute("value", data.data[x].dealer_uid);
                optEle1.appendChild(document.createTextNode(data.data[x].dealer));
                dealerSelect.appendChild(optEle1);
            }
            layui.form.render("select");
        }
    });

    layui.form.on('select(sheetNames)', function(data){
        // console.log("debug select:",data.value);
        // 清理表单中checkbox
        $('.import checkbox').remove();

        // var mappingMembers = document.getElementById("headcheck");
        jsonexcel =  XLSX.utils.sheet_to_json(workbook.Sheets[data.value]);

        // console.log("debug Sheets:",jsonexcel);

        //判断如果sheet页数据为空，则提示
        if (jsonexcel.length == 0) {
            alert("此页无数据，请选择其它sheet！");  
        }else{
            title = Object.keys(jsonexcel[0]);
            // console.log("debug title:",title);
            var Obj = document.getElementById("headcheck");
            for (var x=0 ; x< title.length ; x++){
                var optcheck = document.createElement("input");
                optcheck.setAttribute("type", "checkbox");
                optcheck.setAttribute("name", title[x]);
                optcheck.setAttribute("title", title[x]);
                // optcheck.appendChild(document.createTextNode(title[x]));
                Obj.appendChild(optcheck);
            }
        }
        layui.form.render("");
    });

}

function addOrderTemp(qdata){
    // console.log("debug tempname & title :",tempname,title);
    let rdata = [];
    let tempname = qdata["temp_name"]
    let dealerid = qdata["dealer_id"]
    let uid = uuid();
	for (x in qdata) {
		if (qdata[x] == "on" ) {
			var c = new Object();
			c.temp_name = tempname;
            c.temp_uid = uid;
            c.dealer_id = dealerid;
			c.col_value = x;
			// console.log("debug:",c);
			rdata.push(c);
		}
	}

    // console.log("OrderTemp rdata:",rdata);
    return rdata;
}